/**
 * 主将训练系统最终测试脚本
 * 基于现有测试脚本框架
 */

const WebSocket = require('ws');
const http = require('http');

// 测试配置
const CONFIG = {
  baseUrl: 'http://localhost:3000',
  wsUrl: 'ws://localhost:3000/user-service/websocket',
  testUser: {
    mobile: '13800138000',
    passwordHash: 'e10adc3949ba59abbe56e057f20f883e' // 123456的MD5值
  }
};

class CharacterTrainingTester {
  constructor() {
    this.ws = null;
    this.userId = null;
    this.token = null;
    this.selectedCharacterId = null;
    this.testResults = [];
  }

  async runTest() {
    try {
      console.log('🚀 开始主将训练系统最终测试...\n');

      // 步骤1: HTTP登录
      await this.testHttpLogin();

      // 步骤2: WebSocket连接
      await this.testWebSocketConnection();

      // 步骤3: 查询角色列表
      await this.testGetRoleList();

      // 步骤4: 选择角色
      await this.testSelectRole();

      // 步骤5: 测试1204指令 - 获取训练信息
      await this.testGetTrainingInfo();

      // 步骤6: 测试1205指令 - 获取训练详情
      await this.testGetTrainingDetails();

      // 步骤7: 测试1207指令 - 开始训练
      await this.testStartTraining();

      // 显示测试结果
      this.showTestResults();

      console.log('\n🎉 主将训练系统测试完成！');

    } catch (error) {
      console.error('❌ 测试失败:', error.message);
    } finally {
      if (this.ws) {
        this.ws.close();
        console.log('🔌 WebSocket连接已关闭');
      }
    }
  }

  // HTTP请求方法
  async makeHttpRequest(path, method, data) {
    return new Promise((resolve, reject) => {
      const postData = JSON.stringify(data);
      const options = {
        hostname: 'localhost',
        port: 3000,
        path: path,
        method: method,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(postData)
        }
      };

      const req = http.request(options, (res) => {
        let responseData = '';
        res.on('data', (chunk) => {
          responseData += chunk;
        });
        res.on('end', () => {
          try {
            const response = JSON.parse(responseData);
            resolve(response);
          } catch (error) {
            reject(new Error(`解析响应失败: ${error.message}`));
          }
        });
      });

      req.on('error', (error) => {
        reject(new Error(`HTTP请求失败: ${error.message}`));
      });

      req.write(postData);
      req.end();
    });
  }

  // 1. HTTP登录测试
  async testHttpLogin() {
    console.log('🔐 步骤1: HTTP登录测试...');

    try {
      const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
        mobile: CONFIG.testUser.mobile,
        pwd: CONFIG.testUser.passwordHash
      });

      if (loginData.code === 0 && loginData.data) {
        this.userId = loginData.data.userId;
        this.token = loginData.data.accessToken;
        console.log(`✅ 登录成功: userId=${this.userId}, token=${this.token.substring(0, 8)}...`);
        this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
      } else {
        throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
      }
    } catch (error) {
      console.log('❌ 登录失败:', error.message);
      this.addTestResult('HTTP登录', false, error.message);
      throw error;
    }
  }

  // 2. WebSocket连接测试
  async testWebSocketConnection() {
    console.log('\n🔌 步骤2: WebSocket连接测试...');

    return new Promise((resolve, reject) => {
      const wsUrl = `${CONFIG.wsUrl}?token=${this.token}`;
      this.ws = new WebSocket(wsUrl);

      this.ws.on('open', () => {
        console.log('✅ WebSocket连接成功');
        this.addTestResult('WebSocket连接', true, '连接建立成功');
        resolve();
      });

      this.ws.on('error', (error) => {
        console.error('❌ WebSocket连接失败:', error.message);
        this.addTestResult('WebSocket连接', false, error.message);
        reject(error);
      });

      this.ws.on('message', (data) => {
        try {
          const message = JSON.parse(data.toString());
          console.log('📨 收到消息:', JSON.stringify(message, null, 2));
        } catch (error) {
          console.log('📨 收到原始消息:', data.toString());
        }
      });
    });
  }

  // 3. 查询角色列表
  async testGetRoleList() {
    console.log('\n📋 步骤3: 查询角色列表...');

    return new Promise((resolve) => {
      const message = { c: 3 };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);

      setTimeout(() => {
        console.log('✅ 查询角色列表完成');
        this.addTestResult('查询角色列表', true, '获取角色列表成功');
        resolve();
      }, 1000);
    });
  }

  // 4. 选择角色
  async testSelectRole() {
    console.log('\n🎯 步骤4: 选择角色...');

    return new Promise((resolve) => {
      const message = { c: 4, d: { id: 2001 } };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);

      setTimeout(() => {
        this.selectedCharacterId = 2001;
        console.log('✅ 角色选择完成');
        this.addTestResult('选择角色', true, '选择角色: 测试角色');
        resolve();
      }, 1000);
    });
  }

  // 5. 测试1204指令 - 获取训练信息
  async testGetTrainingInfo() {
    console.log('\n🏋️ 步骤5: 测试1204指令 - 获取训练信息...');

    return new Promise((resolve) => {
      const message = { c: 1204 };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);

      setTimeout(() => {
        console.log('✅ 1204指令测试完成');
        this.addTestResult('1204指令测试', true, '获取训练信息成功');
        resolve();
      }, 2000);
    });
  }

  // 6. 测试1205指令 - 获取训练详情
  async testGetTrainingDetails() {
    console.log('\n📊 步骤6: 测试1205指令 - 获取训练详情...');

    return new Promise((resolve) => {
      const message = { c: 1205 };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);

      setTimeout(() => {
        console.log('✅ 1205指令测试完成');
        this.addTestResult('1205指令测试', true, '获取训练详情成功');
        resolve();
      }, 2000);
    });
  }

  // 7. 测试1207指令 - 开始训练
  async testStartTraining() {
    console.log('\n🚀 步骤7: 测试1207指令 - 开始训练...');

    return new Promise((resolve) => {
      const message = { c: 1207, d: { h: 10 } };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);

      setTimeout(() => {
        console.log('✅ 1207指令测试完成');
        this.addTestResult('1207指令测试', true, '开始训练成功');
        resolve();
      }, 2000);
    });
  }

  // 添加测试结果
  addTestResult(testName, success, message) {
    this.testResults.push({
      name: testName,
      success: success,
      message: message
    });
  }

  // 显示测试结果
  showTestResults() {
    console.log('\n📊 测试结果汇总:');
    console.log('==================================================');
    
    let successCount = 0;
    this.testResults.forEach((result, index) => {
      const status = result.success ? '✅' : '❌';
      console.log(`${index + 1}. ${status} ${result.name}: ${result.message}`);
      if (result.success) successCount++;
    });
    
    console.log('==================================================');
    console.log(`总计: ${successCount}/${this.testResults.length} 项测试通过`);
    
    if (successCount === this.testResults.length) {
      console.log('🎉 所有测试通过！');
    } else {
      console.log('⚠️ 部分测试失败');
    }
  }
}

// 运行测试
if (require.main === module) {
  const tester = new CharacterTrainingTester();
  tester.runTest().catch((error) => {
    console.error('💥 测试执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = { CharacterTrainingTester };
